package com.steam.splace;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.*;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;

import bo.UploadToServer;
import bo.UserFunctions;

import thread.DoThread;
import thread.DoThreadGet;

import dao.DataAccess;
import entity.Message;
import entity.User;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import org.apache.http.HttpEntity;

import com.squareup.picasso.Picasso;
public class ProfileActivity extends Activity {

	private final int viewprofile_tag = 2;
    private final int getfavorite_tag =9;
    private final int edituser_tag =15;
    Menu menu;Handler handler;
    int positionOnSpin=-1;
    Spinner spSex;
    private int serverResponseCode = 0;
    private ImageView imageview;
    private ProgressDialog dialog = null;
    private String upLoadServerUri = null;
    private String returnUrl="";
    private String imagepath="";
    int uid=-1;
    String token="";
    Activity currentActivity;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile_activity);
		currentActivity=this;
		//uid=getUID();
		imageview = (ImageView)findViewById(R.id.imageView_pic);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		spSex = (Spinner) findViewById(R.id.spSex);
		ArrayList<String> list=new ArrayList<String>();
		list.add("Không xác định");
		list.add("Nam");
		list.add("Nữ");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spSex.setAdapter(dataAdapter);
		spSex.setOnItemSelectedListener(new MyEvent());
		fillGUI fill=new fillGUI(ProfileActivity.this);
		fill.execute();
	}
	private class MyEvent implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			positionOnSpin = arg2;
			Log.v("position",arg2+"");
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}
	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btSave) {
			Button bt=(Button)this.findViewById(R.id.btSave);
			bt.setEnabled(false);
			TextView txtEmail = (TextView) findViewById(R.id.lbEmail);
			EditText txtNewPw = (EditText) findViewById(R.id.txtNewPw);
			EditText txtReNewpw = (EditText) findViewById(R.id.txtReNewpw);
			EditText txtAddress = (EditText) findViewById(R.id.txtAddress);
			EditText txtPhone = (EditText) findViewById(R.id.txtPhone);
			String sex="";
			if(positionOnSpin==1)
				sex="1";
			else if(positionOnSpin==2)
				sex="2";
			else
				sex="0";
			//if(txtEmail.getText()!=null&&!txtEmail.getText().toString().trim().equals("")&&txtPassword.getText()!=null&&!txtPassword.getText().toString().trim().equals("")){
			if(validateForm()){
			List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("userid", uid+""));
				params.add(new BasicNameValuePair("email",txtEmail.getText().toString()));
				params.add(new BasicNameValuePair("newpassword",txtNewPw.getText().toString()));
				params.add(new BasicNameValuePair("address",txtAddress.getText().toString()));
				params.add(new BasicNameValuePair("phone",txtPhone.getText().toString()));
				params.add(new BasicNameValuePair("sex",sex));
				params.add(new BasicNameValuePair("avatar",returnUrl));
			for(int i=0;i<params.size();i++)
			{
				
				System.out.println(params.get(i).getName()+"/"+params.get(i).getValue());
			}
				ArrayList l=new ArrayList();
				l.add(edituser_tag);
				l.add(params);
				l.add(token);
			DoThread thread=new DoThread(this);
			thread.execute(l);}
		} else if (id == R.id.btUploadAvatar) {
			new Thread(new Runnable() {
                public void run() {
                     UploadToServer upload=new UploadToServer(currentActivity);        
                     returnUrl=upload.uploadFile(imagepath);
                                              
                }
              }).start();
		} else if (id == R.id.btChooseFile) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(Intent.createChooser(intent, "Choose picture"), 1);
		}
	}
	public boolean validateForm(){
		boolean stt=true;
		EditText txtNewPw = (EditText) findViewById(R.id.txtNewPw);
		EditText txtReNewpw = (EditText) findViewById(R.id.txtReNewpw);
		String alert="";
		if(txtNewPw.getText().toString().trim().length()>0){
		if(txtNewPw.getText().toString().trim().equals("")){
			stt=false;
			alert+="Mật Khẩu không được để trống\n";
			}
		else{
			if(!txtNewPw.getText().toString().trim().equals(txtReNewpw.getText().toString().trim()))
			{stt= false;
			alert+="Nhắc lại mật khẩu không đúng\n";
			}
		}
		if(txtNewPw.getText().toString().trim().length()<8)
			{stt= false;
			alert+="Mật khẩu phải chứa ít nhất 8 kí tự\n";
			}}
		this.findViewById(R.id.btSave).setEnabled(true);
		if(alert.length()>0){
		Toast toast=Toast.makeText(this, alert,
				Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();}
	return stt;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);

		this.menu=menu;
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		if(uid!=-1){
			getMenuInflater().inflate(R.menu.main, menu);}
		else getMenuInflater().inflate(R.menu.menunologin, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.menuSearch) {
			if (!this.getClass().getSimpleName().equals("SearchActivity")) {

				Intent searchIntent = new Intent(this, SearchActivity.class);
				startActivity(searchIntent);
			}
		} else if (item.getItemId() == R.id.menuProfile) {
			if (!this.getClass().getSimpleName().equals("ProfileActivity")) {
				Intent profileIntent = new Intent(this, ProfileActivity.class);
				startActivity(profileIntent);
			}
		}
		else if(item.getItemId() == R.id.SignOut){
			DataAccess da=new DataAccess(this);
			try {
				da.open();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			da.signOut();
			da.close();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			Editor prefsEditor = prefs.edit(); 
			prefsEditor.putInt("uid", -1);
			prefsEditor.putString("token", "");
				prefsEditor.commit();
			this.finish();
			Intent loginIntent = new Intent(this, MainActivity.class);
			startActivity(loginIntent);
		}
		else if(item.getItemId() == R.id.menuSignUp){
			if (!this.getClass().getSimpleName().equals("SignUpActivity")) {

				Intent signUpActivity = new Intent(this, SignUpActivity.class);
				startActivity(signUpActivity);
			}
		}
		else if(item.getItemId() == R.id.menuForgot){
			if (!this.getClass().getSimpleName().equals("ForgotPasswordActivity")) {
				Intent forgotPasswordActivity = new Intent(this, ForgotPasswordActivity.class);
				startActivity(forgotPasswordActivity);
			}
		}
		else if(item.getItemId() == R.id.menuAddPlace){
			if (!this.getClass().getSimpleName().equals("AddPlaceActivity")) {
				Intent addPlaceActivity = new Intent(this, AddPlaceActivity.class);
				startActivity(addPlaceActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSignIn){
			if (!this.getClass().getSimpleName().equals("MainActivity")) {
				Intent mainActivity = new Intent(this, MainActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSearchArea){
			if (!this.getClass().getSimpleName().equals("SearchByAreaActivity")) {
				Intent mainActivity = new Intent(this, SearchByAreaActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuFavorite){
			if (!this.getClass().getSimpleName().equals("FavoriteActivity")) {

				Intent favoriteActivity = new Intent(this, FavoriteActivity.class);
				startActivity(favoriteActivity);
			}
		}
		return true;
	}
	public int getUID(){
		
		DoThreadGet thread1 = new DoThreadGet(this);
		ArrayList params1 = new ArrayList();
		params1.add(getfavorite_tag);
		DataAccess da = new DataAccess(this);
		int uid = -1;
		try {
			da.open();
			User u=da.getUserInUse();
			if (u != null){
				uid = u.getId();
				token=u.getAccessToken();
			}
			else
				uid = -1;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			uid = -1;
		} finally {
			da.close();
		}
		return uid;
	}
	
	
	
	//upload file
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 
           
            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            //imagepath=selectedImageUri.getPath();
            //Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageURI(selectedImageUri);
            imageview.getLayoutParams().height=200;
            imageview.getLayoutParams().width=200;
             
        }
    }
         public String getPath(Uri uri) {

        	   Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        	   cursor.moveToFirst();
        	   String document_id = cursor.getString(0);
        	   document_id = document_id.substring(document_id.lastIndexOf(":")+1);
        	   cursor.close();

        	   cursor = getContentResolver().query( 
        	   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        	   null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        	   cursor.moveToFirst();
        	   String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        	   cursor.close();

        	   return path;
            }
         

    
	public class fillGUI extends AsyncTask<Void, Void, User>{
		Activity contextParent;
		 public fillGUI(Activity ctx)
		 {
			 contextParent=ctx;
		 }
		@Override
		protected User doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			DataAccess da=new DataAccess(contextParent);
			try {
				da.open();
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User u=da.getUserInUse();
			da.close();
			return u;
		}
		@Override
		 protected void onPostExecute(User u) {
			TextView email=(TextView)contextParent.findViewById(R.id.lbEmail);
			EditText phone=(EditText)contextParent.findViewById(R.id.txtPhone);
			EditText address=(EditText)contextParent.findViewById(R.id.txtAddress);
			Button bt=(Button)findViewById(R.id.btSave);
			ImageView ava=(ImageView)contextParent.findViewById(R.id.imageView_pic);
			
			if(u!=null){
			if(u.getPhone().equals("")||u.getAddress().equals("")||u.getSex().equals(""))
				bt.setText("Cập Nhật");
			if(!u.getAvatar().equals(""))
			Picasso.with(contextParent).load(u.getAvatar()).into(ava);
			System.out.println("Avatar:"+ u.getAvatar());
			email.setText(u.getEmail());
			phone.setText(u.getPhone());
				address.setText(u.getAddress());
			 if(u.getSex().equals("1"))
				spSex.setSelection(1);
			else if(u.getSex().equals("2"))
				spSex.setSelection(2);
			else
				spSex.setSelection(0);}
		}
		
		
	}
}
